
<template>
  <div>
    <TopFilter :list="topFilterList" :cols="3" :labelWidth="105" @filterChange="changeHandle"></TopFilter>
    <FilterTable
      ref="table"
      selectionType="single"
      :isSelectColumn="false"
      :columns="columns"
      :fetchapi="fetchapi"
      :params="fetchParams"
      datakey="records"
      columnsRef="ownerQuerylswvq"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="onRowSelectChange"
    >
      <template slot="controls" slot-scope="props">
        <multiuse-button size="small" type="primary" :click="downHandle">导出</multiuse-button>
      </template>
    </FilterTable>
    <!-- <BaseDialog :visible.sync="actions.visible" :title="actions.title" width="300" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <searchDearlerList :resData="this.resData" @dealerData="dealerData" @close="closeSetting('dealer')" />
    </BaseDialog> -->
    <!-- <Drawer :visible.sync="actionsOwner.visible" :title="actionsOwner.title" width="60%" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <ownerQueryPanel :formData="this.resData" @close="closeSetting('owner')" />
    </Drawer> -->
  </div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import { isFormEmpty, notifyAction, findTableItem } from '@/utils';
import { exportExcelFile } from '@/utils/index';
import {  exporturl} from '@/api/omSale/ActualSales/RetailOrders';
import { getDealerLabourHourList, getAllSeries, getModelsBySeries } from '@/api/repair/repairBusiness/labourHour/index.js';
import { getPinpSelect, getChexSelect, getCheModelSelect } from '@/api/repair/repairReception/customer/brand.js';
//import { getDearlerListByTranslate } from '@/api/customerRepair/vehicleOwnerManagement/vehicleChange';
import { getProvince, getCitys, getDistrict, getRegion } from '@/api/customerRepair/customerInfo/ownerVehicleManagement';
import { getOwnerAndVehicleInfo, exportOwnerAndVehicleInfo } from '@/api/customerRepair/customerInfo/ownerVehicleManagement';
import { getListService, exportRepair, exportRepairModel, updateStatesRepairItem, getCarSeries, getCarModels, sendDown } from '@/api/claim/dealer/AuthMaintenance';
import searchDearlerList from '@/pages/customerRepair/vehicleOwnerManagement/vehicleChangeQuery/searchDearlerList';
// import ownerQueryPanel from './ownerQueryPanel';
import moment from 'moment';
import {getModelList} from "@/api/claim/dealer/AuthMaintenance";

export default {
  name: 'ownerAndVehicleQuery',
  components: {
    searchDearlerList
    // ownerQueryPanel
  },
  mixins: [dictionary],
  data() {
    this.selectedData = null;
    this.BaseTable = null;
    this.resData = null;
    this.allSeries = {};
    return {
      topFilterList: this.createTopFilterList(),
      columns: this.createTableColumns(),
      fetchapi: getOwnerAndVehicleInfo,
      fetchParams: {
        xhrAbort: true,
        status:1
      }, //ipa 接口
      actions: { visible: false, title: '', type: '' },
      actionsOwner: { visible: false, title: '', type: '' },
      dealerList: [] // 经销商列表
    };
  },
  mounted() {
    this.BaseTable = this.$refs.table;
    // 查询经销商
    //this.getDearlerListByTranslate();
    // 获取省
    this.getProvine();
    // 获取省市
    this.getRegion();
    this.getAllSeries();
  },
  methods: {
    createTopFilterList() {
      return [
        // {
        //   type: 'INPUT',
        //   label: '经销商',
        //   fieldName: 'ownerCode',
        //   hidden: true,
        //   initialValue: ''
        // },
        // {
        //   type: 'INPUT',
        //   label: '经销商',
        //   fieldName: 'ownerShortName',
        //   placeholder: '请选择...',
        //   initialValue: '',
        //   readonly: true,
        //   unitRender: () => {
        //     return <el-button icon="el-icon-search" onClick={() => this.openHandler('dealer', {})}></el-button>;
        //   }
        // },
        // {
        {
          type: 'INPUT',
          label: '车主姓名',
          fieldName: 'ownerName',
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '车主手机号',
          fieldName: 'mobile'
        },
        {
          type: 'SELECT',
          label: '车系',
          fieldName: 'seriesCode',
          placeholder: '请选择...',
          initialValue: '',
          itemList: this.getCarSeriesData(),
          change: (val) => {
            console.log(val, this.topFilterList);
            if (val) {
              this.getCarModelData(val, 'edit', true);
            } else {
              this.topFilterList.find(item => item.fieldName === 'modelCode').itemList = [];
              this.topFilterList.find(item => item.fieldName === 'modelCode').initialValue = '';
            }

          }
        },
        {
          type: 'SELECT',
          label: '车型',
          fieldName: 'modelCode',
          placeholder: '请选择...',
          itemList: [],
        },
        // {
        //   type: 'RANGE_DATE',
        //   label: '销售日期',
        //   fieldName: 'salesDateStart|salesDateEnd',
        //   initialValue: [
        //     moment(new Date())
        //       .subtract(6, 'month')
        //       .format('YYYY-MM-DD'),
        //     moment(new Date()).format('YYYY-MM-DD')
        //   ]
        // },
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin'
        },
        {
          type: 'INPUT',
          label: '车牌号',
          fieldName: 'license'
        },
        // {
        //   type: 'RANGE_DATE',
        //   label: '交车日期',
        //   fieldName: 'inCarDateStart|inCarDateEnd',
        //   initialValue: [
        //     moment(new Date())
        //       .subtract(6, 'month')
        //       .format('YYYY-MM-DD'),
        //     moment(new Date()).format('YYYY-MM-DD')
        //   ]
        // },
        {
          type: 'RANGE_DATE',
          label: '开票日期',
          fieldName: 'invoiceDateStart|invoiceDateEnd',
          initialValue: [
            moment(new Date())
              .subtract(6, 'month')
              .format('YYYY-MM-DD'),
            moment(new Date()).format('YYYY-MM-DD')
          ]
        },
        {
          type: 'RANGE_DATE',
          label: '保修起始日期',
          fieldName: 'wrtBeginDateStart|wrtBeginDateEnd',
          initialValue: [
            moment(new Date())
              .subtract(1, 'month')
              .format('YYYY-MM-DD'),
            moment(new Date()).format('YYYY-MM-DD')
          ],
          rules: [{ required: true, message: '保修起始日期', trigger: 'blur' }]
        },
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          fixed: 'left',
          // sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        // {
        //   title: '操作',
        //   dataIndex: 'column-action',
        //   width: 70,
        //   render: props => {
        //     return (
        //       <div style="text-align:center">
        //         <el-button size="mini" type="text" onClick={() => this.openHandler('detail', props.row)}>
        //           明细
        //         </el-button>
        //       </div>
        //     );
        //   }
        // },
        {
          title: '车主姓名',
          dataIndex: 'ownerName',
          width: 90,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '车主手机号',
          dataIndex: 'mobile',
          width: 90,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '车主性别',
          dataIndex: 'gender',
          width: 90,
          sorter:true,
          showOverflowTooltip: true,
          render: props => {
            return <span>{this.createDictText(props.row.gender, 1002)}</span>;
          }
        },
        {
          title: 'VIN',
          dataIndex: 'vin',
          width: 90,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '车牌号',
          dataIndex: 'license',
          width: 90,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '电机号',
          dataIndex: 'motorNo1',
          width: 90,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '品牌',
          width: 90,
          dataIndex: 'brandName',
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '车系',
          width: 90,
          dataIndex: 'seriesName',
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '车型',
          dataIndex: 'modelName',
          width: 90,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '颜色',
          dataIndex: 'color',
          width: 90,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '配置',
          dataIndex: 'apackage',
          width: 90,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '销售经销商简称',
          dataIndex: 'dealerName',
          width: 150,
          sorter:true,
          showOverflowTooltip: true,
          // render: props => {
          //   return <span>{this.getText(props.row.OWNER_CODE)}</span>;
          // }
        },
        {
          title: '销售经销商代码',
          dataIndex: 'dealerCode',
          width: 150,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '发动机号',
          dataIndex: 'engineNo',
          width: 90,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '变速器号',
          dataIndex: 'gearBox',
          width: 90,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '电池编号',
          dataIndex: 'batteryNo',
          width: 90,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '交车日期',
          dataIndex: 'inCarDate',
          width: 90,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '开票日期',
          dataIndex: 'invoiceDate',
          width: 90,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '保修起始日期',
          dataIndex: 'wrtBeginDate',
          width: 90,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '客户编号',
          dataIndex: 'ownerNo',
          width: 90,
          sorter:true,
          showOverflowTooltip: true,
        },
        {
          title: '销售顾问',
          dataIndex: 'consultant',
          width: 90,
          sorter:true,
          showOverflowTooltip: true,
          //dictItems: this.createDictList(8011)
        },
        // {
        //   title: '省份',
        //   dataIndex: 'provinceId',
        //   sorter: true,
        //   render: props => {
        //     return <span>{this.createRegionText(props.row.provinceId)}</span>;
        //   }
        // },
        {
          title: '省份',
          dataIndex: 'province',
          width: 90,
          dictItems: [],
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '城市',
          dataIndex: 'city',
          width: 90,
          dictItems: [],
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '区/县',
          dataIndex: 'district',
          width: 90,
          dictItems: [],
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '地址',
          dataIndex: 'address',
          width: 150,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '邮编',
          dataIndex: 'zipCode',
          width: 90,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: 'Email',
          dataIndex: 'email',
          width: 90,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '是否延保',
          dataIndex: 'isWarranty',
          width: 90,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '延保类型',
          dataIndex: 'warrantyType',
          width: 90,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '是否赠送保养',
          dataIndex: 'isGiveMaintain',
          width: 150,
          sorter:true,
          showOverflowTooltip: true
        },
        {
          title: '免费保养次数',
          dataIndex: 'freeRepairTimes',
          width: 150,
          sorter:true,
          showOverflowTooltip: true
        },
      ];
    },
    changeHandle(val) {
      // 搜索和重置都走
      let params = { ...this.fetchParams, ...val, ...{ xhrAbort: false } };
      if (params.ownerShortName && params.ownerShortName.length) {
        params.ownerCode = this.topFilterList.find(x => x.fieldName === 'ownerCode').initialValue;
      } else {
        params.ownerCode = undefined;
      }
      if(!params.wrtBeginDateStart) {
          this.$notify.warning({ title: '提示信息', message: '保修起始开始日期不可为空！' });
          return
        }
        if(!params.wrtBeginDateEnd) {
          this.$notify.warning({ title: '提示信息', message: '保修起始结束日期不可为空！' });
          return
        }
      // if (!val.ownerName && !val.license && !val.vin && !val.salesDateStart && !val.salesDateEnd) {
      //   return this.$notify.warning({ title: '提示信息', message: 'vin,车牌号,客户姓名,销售日期必填其一' });
      // }
      // if (val.salesDateStart || val.salesDateEnd) {
      //   let diffMonth = moment(val.salesDateEnd).diff(moment(val.salesDateStart), 'months');
      //   if (diffMonth > 11) return this.$notify.warning({ title: '提示信息', message: '销售起止日期跨度不能超过一年' });
      // }
      this.fetchParams = params;
    },
    getCarSeriesData() {
      let dataArr = [];
      let tempArr = [];
      getCarSeries().then((res) => {
        if (res.resultCode === 200) {
          res.data.forEach((item) => {
            if (item.SERIES_CODE && !tempArr.includes(item.SERIES_CODE)) {
              tempArr.push(item.SERIES_CODE);
              dataArr.push({ text: item.SERIES_CODE, value: item.SERIES_CODE, id: item.SERIES_ID });
            }
          });
          this.seriesList = dataArr;
        }
      });
      return dataArr;
    },

    getCarModelData(code, type, isTopFilter = false) {
      let series = this.seriesList.find(item => item.text === code);
      let dataArr = [];
      console.log(series)
      if (series && series.id) {
        getModelList(null, series.id, null).then((res) => {
          console.log(res)
          if (res.resultCode === 200) {
            if (type == 'edit' && isTopFilter) {
              this.topFilterList.find(item => item.fieldName === 'modelCode').initialValue = '';
              this.topFilterList.find(item => item.fieldName === 'modelCode').itemList = res.data.map(x => ({ text: x.modelName, value: x.modelCode }));
            }
            res.data.forEach((item) => {
              dataArr.push({ text: item.modelName, value: item.modelCode })
            })
          }
          this.modelList = dataArr;
        });
      }
    },
    async getAllSeries() {
      let res = await getChexSelect('null');
      if (res.resultCode === 200) {
        let series = res.data.map(x => {
          return { value: x.seriesCode, text: x.seriesName };
        });
        this.topFilterList.find(x => x.fieldName === 'seriesCode').itemList = series;
        this.allSeries = res.data;
      }
    },
    async getModelsBySeries(val) {
      let res = await getModelList(null, val, null);
      if (res.resultCode === 200) {
        let models = res.data.map(x => {
          return { value: x.modelCode, text: x.modelName };
        });
        this.topFilterList.find(x => x.fieldName === 'modelLabourCode').initialValue = '';
        this.topFilterList.find(x => x.fieldName === 'modelLabourCode').itemList = models;
      }
    },
    // collapseHandle() {
    //   this.$nextTick(this.BaseTable.EXECUTE_RESET_HEIGHT);
    // },
    onRowSelectChange(row) {
      if (!row.length) {
        this.selectedData = null;
      } else {
        this.selectedData = row[0];
      }
    },
    // 获取经销商数据
    // dealerData(val) {
    //   this.topFilterList.find(x => x.fieldName === 'ownerCode').initialValue = val.dealerCode;
    //   this.topFilterList.find(x => x.fieldName === 'ownerShortName').initialValue = val.dealerShortname;
    //   this.closeSetting('dealer');
    // },
    // 关闭经销商页面
    closeSetting(type) {
      if (type === 'dealer') {
        this.actions.visible = false;
      } else if (type === 'owner') {
        this.actionsOwner.visible = false;
      }
    },
    // 查询全部经销商列表
    // async getDearlerListByTranslate() {
    //   const res = await getDearlerListByTranslate();
    //   console.log(JSON.stringify(res.data)+"+++++++++++++++++++++++++++++==res.data")
    //   if (res.resultCode === 200) {
    //     if (res.errMsg) {
    //       notifyAction(res.errMsg, 'error');
    //     } else {
    //       this.dealerList = res.data;
    //     }
    //   }
    // },
    // 翻译经销商列表
    // getText(val) {
    //   return this.dealerList.find(x => x.dealerCode === val) ? this.dealerList.find(x => x.dealerCode === val).dealerName : '';
    // },
    // 清空下拉框表当控件的值和下拉列表
    clearFormItem(item) {
      item.initialValue = undefined;
      item.itemList = [];
    },
    //获取省
    async getProvine() {
      const res = await getProvince();
      this.topFilterList.find(item => item.fieldName === 'province').itemList = res.data.map(x => ({ value: x.regionCode + '', text: x.regionName }));
    },
    // 获取市下拉框
    async provinceChange(regionId) {
      this.clearFormItem(this.topFilterList.find(item => item.fieldName === 'city'));
      this.clearFormItem(this.topFilterList.find(item => item.fieldName === 'distinct'));
      if (!regionId) return;
      const res = await getCitys(regionId);
      this.topFilterList.find(item => item.fieldName === 'city').itemList = res.data.map(x => ({ value: x.regionCode, text: x.regionName }));
    },
    // 获取区下拉框
    async cityChange(regionId) {
      this.clearFormItem(this.topFilterList.find(item => item.fieldName === 'distinct'));
      if (!regionId) return;
      const res = await getDistrict(regionId);
      this.topFilterList.find(item => item.fieldName === 'distinct').itemList = res.data.map(x => ({ value: x.regionCode, text: x.regionName }));
    },
    // 获取省市
    async getRegion() {
      const allRegion = await getRegion();
      let regionList = allRegion.data.map(x => ({ value: x.regionCode + '', text: x.regionName }));
      let targetTableItems = [findTableItem(this.columns, 'province'), findTableItem(this.columns, 'city'), findTableItem(this.columns, 'district')];
      targetTableItems.forEach(item => {
        item.dictItems = regionList;
      });
    },
    // 车主导出
    async downHandle() {
      let json = Object.assign({}, { CODE: 'CODE_00000271' }, this.fetchParams);
      let res = await exporturl(json);
      if (res.resultCode == 200) {
        this.$router.push('/admin/auth/oem/downloadCenter');
      }
    },
  }
};
</script>
<style lang="less" scoped></style>
